package compiler;

import java.util.Hashtable;

public class ScopeManager {
    private Hashtable<String, Object> globals;
    private Hashtable<String, Object> locals;
    
    public ScopeManager() {
        globals = new Hashtable<String, Object>();
        locals  = new Hashtable<String, Object>();
    }
    
    /**
     * Insert a key in the global table
     * @param key The key which references the object
     * @param value The value to be inserted
     * @return null if there was no object at this position or the previous object
     */
    public Object insertGlobal(String key, Object value) {
       return globals.put(key, value);
    }
 
    /**
     * Insert a key in the local table
     * @param key The key which references the object
     * @param value The value to be inserted
     * @return null if there was no object at this position or the previous object
     */    
    public Object insertLocal(String key, Object value) {
       return locals.put(key, value);
    }
    
    /**
     * Gets an object in the local table
     * @param key The key which references the object
     * @return the object or null if there is no object referenced by the key
     */
    public Object getLocal(Object key) {
       return locals.get(key);
    }
    
    /**
     * Gets an object in the global table
     * @param key The key which references the object
     * @return the object or null if there is no object referenced by the key
     */    
    public Object getGlobal(Object key) {
       return globals.get(key);
    }
    
    
    /**
     * Gets an object, first search in the local table and then in the global table
     * @param key The key which references the object
     * @return the object or null if there is no object referenced by the key
     */    
    public Object get(String key) {
        Object o;
        // Try to find in the local scope first
        if ((o = locals.get(key)) != null)
            return o;
        else
            return globals.get(key);
    }
 
    /**
     * Clears the local table
     */
    public void clearLocals() {
         locals.clear(); 
    }
}